<template>
  <div class="announcement-manager">
    <div class="header">
      <a-form :model="searchParams" layout="inline" @finish="doSearch">
        <a-form-item label="标题">
          <a-input v-model:value="searchParams.title" placeholder="请输入标题" />
        </a-form-item>
        <a-button type="primary" htmlType="submit">搜索</a-button>
      </a-form>

      <a-button type="primary" @click="showPublishModal">
        <template #icon>
          <PlusOutlined />
        </template>
        发布新公告
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      :loading="loading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'createTime'">
          <span>{{ formatTime(record.createTime) }}</span>
        </template>
        <template v-else-if="column.dataIndex === 'isActive'">
          <div class="isActive">
            <div v-if="record.isActive === 0">
              <a-tag color="blue">草稿</a-tag>
            </div>
            <div v-else-if="record.isActive === 1">
              <a-tag color="green">已发布</a-tag>
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <div class="action-buttons">
            <!-- 只有草稿状态的公告显示编辑按钮 -->
            <a-button
              v-if="record.isActive === 0"
              type="link"
              size="small"
              @click="showEditModal(record)"
            >
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除公告吗？"
              @confirm="() => doDelete(record.id)"
              okText="确定"
              cancelText="取消"
            >
              <a-button type="link" danger size="small" style="padding-left: 20px">删除</a-button>
            </a-popconfirm>
          </div>
        </template>
      </template>
    </a-table>

    <!-- 发布/编辑公告弹窗 -->
    <a-modal
      v-model:visible="publishVisible"
      :title="isEditMode ? '编辑公告' : '发布新公告'"
      width="600px"
      :confirm-loading="publishing"
      @ok="handlePublish"
      @cancel="handleCancelPublish"
      :okText="isEditMode ? '更新' : '发布'"
      cancelText="存为草稿"
    >
      <a-form ref="publishFormRef" :model="publishForm" :rules="formRules" layout="vertical">
        <a-form-item label="公告标题" name="title">
          <a-input
            v-model:value="publishForm.title"
            placeholder="请输入公告标题"
            :maxlength="100"
          />
        </a-form-item>

        <a-form-item label="公告内容" name="content">
          <a-textarea
            v-model:value="publishForm.content"
            placeholder="请输入公告内容"
            :rows="5"
            :maxlength="1000"
            show-count
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  addAnnouncementUsingPost,
  deleteAnnouncementUsingPost,
  listAnnouncementVoByPageUsingPost,
  updateAnnouncementUsingPost,
} from '@/api/announcementController'

// 列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 180,
  },
  {
    title: '标题',
    dataIndex: 'title',
    ellipsis: true,
  },
  {
    title: '内容',
    dataIndex: 'content',
    ellipsis: true,
  },
  {
    title: '公告状态',
    dataIndex: 'isActive',
    ellipsis: true,
  },
  {
    title: '发布时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
  },
]

// 数据列表
const dataList = ref<any[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索参数
const searchParams = reactive({
  current: 1,
  pageSize: 10,
  title: '',
})

// 分页参数
const pagination = computed(() => ({
  current: searchParams.current,
  pageSize: searchParams.pageSize,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
}))

// 发布公告相关状态
const publishVisible = ref(false)
const publishing = ref(false)
const publishFormRef = ref()
const isEditMode = ref(false)
const currentEditId = ref<number | null>(null)

// 发布表单数据
const publishForm = reactive({
  title: '',
  content: '',
  isActive: 1, // 默认为已发布状态
})

// 表单验证规则
const formRules = reactive({
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
})

// 格式化时间
const formatTime = (time: string) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取公告列表
const getAnnouncementList = async () => {
  loading.value = true
  try {
    const res = await listAnnouncementVoByPageUsingPost({
      ...searchParams,
    })

    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records || []
      total.value = res.data.data.total || 0
    } else {
      message.error(res.data.message || '获取公告列表失败')
    }
  } catch (error) {
    message.error('获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 切换表格页数
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  getAnnouncementList()
}

// 删除公告
const doDelete = async (id: number) => {
  try {
    const res = await deleteAnnouncementUsingPost({
      id: id,
    })

    if (res.data.code === 0 && res.data.data) {
      message.success('公告删除成功')
      getAnnouncementList()
    } else {
      message.error(res.data.message || '删除公告失败')
    }
  } catch (error) {
    message.error('删除公告失败')
  }
}

// 搜索
const doSearch = () => {
  searchParams.current = 1
  getAnnouncementList()
}

// 显示发布弹窗
const showPublishModal = () => {
  isEditMode.value = false
  publishForm.title = ''
  publishForm.content = ''
  publishForm.isActive = 1
  publishVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record: any) => {
  isEditMode.value = true
  currentEditId.value = record.id
  publishForm.title = record.title
  publishForm.content = record.content
  publishForm.isActive = record.isActive
  publishVisible.value = true
}

// 处理发布/编辑公告
const handlePublish = async () => {
  try {
    // 表单验证
    await publishFormRef.value.validate()

    publishing.value = true

    if (isEditMode.value) {
      // 编辑公告
      const res = await updateAnnouncementUsingPost({
        id: currentEditId.value,
        title: publishForm.title,
        content: publishForm.content,
        isActive: 1, // 编辑后直接发布
      })

      if (res.data.code === 0 && res.data.data) {
        message.success('公告更新成功')
        publishVisible.value = false
        // 重置表单
        publishForm.title = ''
        publishForm.content = ''
        publishForm.isActive = 1
        // 刷新列表
        getAnnouncementList()
      } else {
        message.error(res.data.message || '更新公告失败')
      }
    } else {
      // 发布新公告
      const res = await addAnnouncementUsingPost({
        title: publishForm.title,
        content: publishForm.content,
        isActive: 1, // 发布状态
      })

      if (res.data.code === 0 && res.data.data) {
        message.success('公告发布成功')
        publishVisible.value = false
        // 重置表单
        publishForm.title = ''
        publishForm.content = ''
        publishForm.isActive = 1
        // 刷新列表
        getAnnouncementList()
      } else {
        message.error(res.data.message || '发布公告失败')
      }
    }
  } catch (error) {
    message.error(isEditMode.value ? '更新公告失败' : '发布公告失败')
  } finally {
    publishing.value = false
  }
}

// 存为草稿
const handleCancelPublish = async () => {
  try {
    // 表单验证
    await publishFormRef.value.validate()

    publishing.value = true

    if (isEditMode.value) {
      // 编辑公告并保存为草稿
      const res = await updateAnnouncementUsingPost({
        id: currentEditId.value,
        title: publishForm.title,
        content: publishForm.content,
        isActive: 0,
      })

      if (res.data.code === 0 && res.data.data) {
        message.success('公告已保存为草稿')
        publishVisible.value = false
        // 重置表单
        publishForm.title = ''
        publishForm.content = ''
        publishForm.isActive = 1
        // 刷新列表
        getAnnouncementList()
      } else {
        message.error(res.data.message || '保存草稿失败')
      }
    } else {
      // 新增公告并保存为草稿
      const res = await addAnnouncementUsingPost({
        title: publishForm.title,
        content: publishForm.content,
        isActive: 0,
      })

      if (res.data.code === 0 && res.data.data) {
        message.success('公告已保存为草稿')
        publishVisible.value = false
        // 重置表单
        publishForm.title = ''
        publishForm.content = ''
        publishForm.isActive = 1
        // 刷新列表
        getAnnouncementList()
      } else {
        message.error(res.data.message || '保存草稿失败')
      }
    }
  } catch (error) {
    message.error('保存草稿失败')
  } finally {
    publishing.value = false
  }
}

onMounted(() => {
  getAnnouncementList()
})
</script>

<style scoped>
.announcement-manager {
  max-width: 100%;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-radius: 8px;
}

.ant-form {
  margin-bottom: 0;
}

.ant-table {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

:deep(.ant-btn-link) {
  padding: 0;
  height: auto;
}

:deep(.ant-modal-header) {
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

:deep(.ant-modal-title) {
  font-weight: 600;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}
</style>
